package com.example.chentian.myzhihudaily.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.webkit.WebView;

import com.example.chentian.myzhihudaily.R;
import com.example.chentian.myzhihudaily.api.ZhiHuDailyAPI;
import com.example.chentian.myzhihudaily.been.ContentBeen;
import com.example.chentian.myzhihudaily.service.ContentService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by chentian on 12/04/2017.
 */

public class DetaiContentActivity extends Activity {
    String contentId;
    WebView contentView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_layout);

        init();
        fillContent();
    }

    private void init(){
        Intent intent = getIntent();
        contentId = intent.getStringExtra("contentId");
        contentView = (WebView) findViewById(R.id.content_webview);
    }

    //进行网络请求，请求首页的详细内容
    private void fillContent() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ZhiHuDailyAPI.contentDetail)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        final ContentService service =  retrofit.create(ContentService.class);
        Call<ContentBeen> call =  service.getContent(contentId);
        call.enqueue(new Callback<ContentBeen>() {
            @Override
            public void onResponse(Call<ContentBeen> call, Response<ContentBeen> response) {
                //成功
                if(response.isSuccessful()&&response.body()!=null){
                    //解析成功
                    Log.d("TAG", "onResponse: 解析成功");
                    String htmlContent = response.body().getBody();

                    contentView.loadDataWithBaseURL("x-data://base", htmlContent, "text/html", "utf-8", null);
                }else{
                    //解析失败
                    Log.d("TAG", "onResponse: 解析失败");
                }
            }

            @Override
            public void onFailure(Call<ContentBeen> call, Throwable t) {
                //失败
                Log.d("TAG", "onFailure: 响应失败");
            }
        });
    }
}
